package com.slicktechnologies.client.views.contract;
import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.view.client.RowCountChangeEvent;
import com.simplesoftwares.client.library.appskeleton.AppMemory;
import com.simplesoftwares.client.library.appstructure.SearchPopUpScreen;
import com.simplesoftwares.client.library.appstructure.SuperTable;
import com.simplesoftwares.client.library.appstructure.formscreen.FormScreen;
import com.simplesoftwares.client.library.appstructure.formscreen.FormScreenPresenter;
import com.simplesoftwares.client.library.appstructure.search.Filter;
import com.simplesoftwares.client.library.appstructure.search.MyQuerry;
import com.simplesoftwares.rebind.annatonations.EntityNameAnnotation;
import com.slicktechnologies.client.services.CsvService;
import com.slicktechnologies.client.services.CsvServiceAsync;
import com.slicktechnologies.client.services.EmailService;
import com.slicktechnologies.client.services.EmailServiceAsync;
import com.slicktechnologies.client.utility.AppConstants;
import com.slicktechnologies.client.utility.GeneratedVariableRefrence;
import com.slicktechnologies.shared.Contract;
import com.slicktechnologies.shared.Sales;

/**
 * FormScreen presenter template.
 */

public class ContractPresenter extends FormScreenPresenter<Contract> implements RowCountChangeEvent.Handler{

	//Token to set the concrete FormScreen class name
	public  ContractForm form;
	
	EmailServiceAsync emailService=GWT.create(EmailService.class);
	final ContractServiceAsync async=GWT.create(ContractService.class);
	
	CsvServiceAsync csvservice=GWT.create(CsvService.class);
	
	public ContractPresenter  (FormScreen<Contract> view, Contract model) {
		super(view, model);
		form=(ContractForm) view;
		form.getSaleslineitemtable().getTable().addRowCountChangeHandler(this);
	}

	@Override
	public void reactToProcessBarEvents(ClickEvent e) {
		
		InlineLabel label=(InlineLabel) e.getSource();
		String text=label.getText().trim();

		
		
		
		
		if(text.equals(AppConstants.Sucessful))
			reactToSucessFull();
		if(text.equals(AppConstants.Unsucessful))
			reactToUnSucessFull();
		if(text.equals(AppConstants.DIAGOSED))
			reactToDiagnosed();
		if(text.equals(AppConstants.CLOSE))
			reactToClose();
		
		
		if(text.equals("New"))
			reactToNew();
		if(text.equals("Email"))
			reactOnEmail();
		

	}

	@Override
	public void reactOnPrint() {
		final String url = GWT.getModuleBaseURL() + "pdfservice"+"?Id="+model.getId()+"&"+"type="+"c";
		 Window.open(url, "test", "enabled");


	}
	
	public void reactOnJobCard()
	{
		final String url = GWT.getModuleBaseURL() + "jobcardpdf"+"?Id="+model.getId();
		 Window.open(url, "test", "enabled");
	}

	

	@Override
	public void reactOnDownload() {
		super.reactOnDownload();
		
		ArrayList<Contract> custarray=new ArrayList<Contract>();
		List<Contract> list=(List<Contract>) form.getSearchpopupscreen().getSupertable().getDataprovider().getList();
		
		custarray.addAll(list);
		
		csvservice.setcontractlist(custarray, new AsyncCallback<Void>() {

			@Override
			public void onFailure(Throwable caught) {
				System.out.println("RPC call Failed"+caught);
				
			}

			@Override
			public void onSuccess(Void result) {
				String gwt=com.google.gwt.core.client.GWT.getModuleBaseURL();
				final String url=gwt + "csvservlet"+"?type="+6;
				Window.open(url, "test", "enabled");
			}
		});

	}

	public void reactOnEmail()
	{
		//Quotation Entity patch patch patch
		emailService.initiateEmail((Sales) model,new AsyncCallback<Void>() {

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Resource Quota Ended ");
				caught.printStackTrace();
				
			}

			@Override
			public void onSuccess(Void result) {
				Window.alert("Email Sent Sucessfully !");
				
			}
		});
	}

	/**
	 * Method token to make new model
	 */
	@Override
	protected void makeNewModel() {
		model=new Contract();
	}




	public static ContractForm initalize()
	{
		ContractForm form=new  ContractForm();

		ContractPresenterTable gentable=new ContractPresenterTableProxy();
		gentable.setView(form);
		gentable.applySelectionModle();
		ContractPresenterSearch.staticSuperTable=gentable;
		ContractPresenterSearchProxy searchpopup=new ContractPresenterSearchProxy();
		form.setSearchpopupscreen(searchpopup);


		ContractPresenter  presenter=new ContractPresenter(form,new Contract());
		AppMemory.getAppMemory().stickPnel(form);
		return form;
	}

	@EntityNameAnnotation(EntityName = "com.slicktechnologies.shared.Contract")
	public static  class ContractPresenterSearch extends SearchPopUpScreen<Contract>{

		@Override
		public MyQuerry getQuerry() {
			// TODO Auto-generated method stub
			return null;
		}};

		@EntityNameAnnotation(EntityName = "com.slicktechnologies.shared.Contract")
		public static class ContractPresenterTable extends SuperTable<Contract> implements GeneratedVariableRefrence{

			@Override
			public Object getVarRef(String varName) {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public void createTable() {
				// TODO Auto-generated method stub

			}

			@Override
			protected void initializekeyprovider() {
				// TODO Auto-generated method stub

			}

			@Override
			public void addFieldUpdater() {
				// TODO Auto-generated method stub

			}

			@Override
			public void setEnable(boolean state) {
				// TODO Auto-generated method stub

			}

			@Override
			public void applyStyle() {
				// TODO Auto-generated method stub

			}} ;

			
			
			private void reactToPayment()
			{
				form.getPaymentComposite().bankbranch.setEnabled(true);
				form.getPaymentComposite().bankname.setEnabled(true);
				form.getPaymentComposite().chequenumber.setEnabled(true);
				form.getPaymentComposite().chequeDate.setEnabled(true);
				form.getPaymentComposite().cashamt.setEnabled(true);
				form.getPaymentComposite().credidamt.setEnabled(true);
				form.getPaymentComposite().cheqamt.setEnabled(true);
				form.btnAddPayment.setEnabled(true);
			}
			
			private void reactToNew()
			{
				form.setToNewState();
				initalize();
			}
			
			private void reactToSucessFull()
			{
				model.setStatus(Contract.SUCESSFUL);
				changeStatus("Fail to mark Un Sucessful !","Marked Sucessful !",Contract.SUCESSFUL);
			}
			
			private void reactToUnSucessFull()
			{
				model.setStatus(Contract.UNSUCESSFUL);
				changeStatus("Fail to mark Un Sucessful !","Marked Un Sucessful !",Contract.UNSUCESSFUL);
			}
			
			private void reactToDiagnosed()
			{
				model.setStatus(Contract.DIAGNOSED);
				changeStatus("Fail to send Diagnosis Message !","Diagnosis Message Sent !",Contract.DIAGNOSED);
			}
			
			private void reactToClose()
			{
				model.setStatus(Contract.CLOSED);
				changeStatus("Failed to Close !","Closed Successfuly !",Contract.CLOSED);
			}
			
			
			
			private void changeStatus(final String failureMessage,final String successMessage,final String status)
			{
				form.showWaitSymbol();
				async.changeStatus(model,new AsyncCallback<Void>() {

					@Override
					public void onFailure(Throwable caught) {
						form.showDialogMessage(failureMessage);
						caught.printStackTrace();
						form.hideWaitSymbol();
					}

					@Override
					public void onSuccess(Void result) {
						form.showDialogMessage(successMessage);
						form.hideWaitSymbol();
						form.tbQuotationStatus.setText(status);
						form.setMenuAsPerStatus();
						
						
					}
				});

					
			}
			
			@Override
			public void onRowCountChange(RowCountChangeEvent event) 
			{
			    double total=form.getSaleslineitemtable().calculateTotal();
			    form.getPaymentComposite().getTotalAmt().setValue(total);
				form.getPaymentComposite().setAmount();
			    
			}
			
			
			

		
}
